package org.jground.zk.util;

import java.util.HashSet;
import java.util.Set;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.jground.rx.RXPrincipalMethods;
import org.jground.rx.RXSystem;
import org.zkoss.zk.ui.Component;
import org.zkoss.zk.ui.event.Event;
import org.zkoss.zk.ui.event.EventThreadInit;

public class RXEventThreadInit implements EventThreadInit {

    private static Log logger = LogFactory.getLog(RXEventThreadInit.class);

    /*
     * INIT CLEAR TASKS STUFF
     */
    private final static Set<Runnable> initClearTasks = new HashSet<Runnable>();

    public static void addInitClearTask(Runnable runnable) {
        initClearTasks.add(runnable);
    }

    private void runInitClearTasks() {
        for (Runnable runnable : initClearTasks) {
            runnable.run();
        }
    }

    private RXPrincipalMethods methods;

    public RXEventThreadInit() {
        logger.debug("RUN constructor ");
    }

    public void prepare(Component comp, Event event) throws Exception {
        logger.debug("START prepare ");
        methods = RXSystem.getRXPrincipalMethods();
        logger.debug("END prepare ");
    }

    // -- EventThreadInit --//
    /** Initial the event processing thread at this method. */
    public boolean init(Component comp, Event evt) {
        logger.debug("START init ");
        RXSystem.setRXPrincipalMethods(methods);
        // bindPrincipalMethodsToThread(comp);
        runInitClearTasks();
        logger.debug("END init ");
        return true;
    }

}